<template>
	<a-drawer
		:title="formData.id ? '编辑角色' : '增加角色'"
		:width="500"
		:visible="visible"
		:destroy-on-close="true"
		:body-style="{ paddingBottom: '80px' }"
		:footer-style="{ textAlign: 'right' }"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="角色编号：" name="code">
				<a-input v-model:value.trim="formData.code" placeholder="请输入角色编号" allow-clear :disabled="formData.id"/>
			</a-form-item>
			<a-form-item label="角色名称：" name="name">
				<a-input v-model:value.trim="formData.name" placeholder="请输入角色名称" allow-clear/>
			</a-form-item>
			<a-form-item label="角色描述：" name="roleDesc">
				<a-textarea v-model:value="formData.roleDesc" placeholder="请输入描述" :rows="4"/>
			</a-form-item>
			<a-form-item label="排序：" name="sortCode">
				<a-slider v-model:value="formData.sortCode" :max="100"/>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" :loading="submitLoading" @click="onSubmit">保存</a-button>
		</template>
	</a-drawer>
</template>

<script setup name="roleForm">
	import { message } from 'ant-design-vue'
	import {required} from '@/utils/formRules'
	import {getCurrentInstance} from 'vue'
	import orgApi from '@/api/sys/orgApi'
	import roleApi from '@/api/sys/roleApi'
	import {cloneDeep} from "lodash-es";

	// 定义emit事件
	const emit = defineEmits({successful: null})
	const {proxy} = getCurrentInstance()
	// 默认是关闭状态
	let visible = $ref(false)
	const formRef = ref()
	// 表单数据，也就是默认给一些数据
	const formData = ref({})
	// 定义机构元素
	const treeData = ref([])
	const submitLoading = ref(false)

	// 打开抽屉
	const onOpen = (record) => {
		visible = true
		formData.value = {
			sortCode: 99
		}
		if (record) {
			formData.value = Object.assign({}, record)
		}
		// 获取机构树并加入顶级
		orgApi.orgTree().then((res) => {
			treeData.value = res
		})
	}
	// 关闭抽屉
	const onClose = () => {
		visible = false
	}
	// 默认要校验的
	const formRules = {
		code: [required('请输入角色编码')],
		name: [required('请输入角色名称')],
		sortCode: [required('请选择排序')]
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				submitLoading.value = true
				const formDataParam = cloneDeep(formData.value)
				formDataParam.category = 'GLOBAL'
				roleApi
					.submitForm(formDataParam, !formDataParam.id)
					.then(() => {
						message.success('保存成功')
						visible = false
						emit('successful')
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
